import {Toast} from 'mint-ui';
export default {
	isdev: function(env) {
		var env = process.env.NODE_ENV;
		return env === 'development' ? '/cxb' : '';
	},
  //返回域名方法
  isEnv:function(domainName){
    var envlist = {
      "prod":"chexiang",
      "pre" :"chexiangpre",
      "sit" : "chexiangsit",
      "development" : "chexiangpre"
    }
    return domainName+"."+envlist[process.env.NODE_ENV]+".com"
  },
	/*getIsLogin: function() {
		var backUrl = this.isdev() + "/user/checkLogin.htm",
			result;
		var data = this.$http.post({
			url: backUrl,
			type: 'POST',
			async: false,
			success: function(d) {
				result = d.result == 1 ? true : false;
			}
		});

		return result;
	},*/
	getLocation: function() {
		var pathname = window.location.pathname;
		var indexNext = pathname.indexOf("/", 0);
		return pathname.substr(0, indexNext);
	},
	goLogin: function() {
		window.location.href = this.getLocation() + "/user/toLogin.htm?targetUrl=" + encodeURIComponent(window.location.href);
	},
	setTitle:function(title) {
		  document.title = title;
		  var i = document.createElement('iframe');
		  //i.src = 'http://s1.cximg.com/msweb02/resource/comm/images/favicon.ico';
		  i.style.display = 'none';
		  i.onload = function() {
		    setTimeout(function(){
		      i.remove();
		    }, 9)
		  }
		  document.body.appendChild(i);
	},
	ANA_Analytics:function(){//埋点
		(new Analytics).scan();//打点CA绑定数据
		//埋点逻辑
	  var scriptBox = document.getElementById("analyticsScript");
	  var getLink = scriptBox.getAttribute('sr');

	  if(scriptBox.getAttribute('src')){
	  	window.ANA.reconfig('').getDate().dataProcess().send();//埋点
	  }else{
	  	scriptBox.setAttribute("src",window._caProtocol + getLink + '?t=' + new Date().getTime());
	  }
		console.log('埋点再启动');
	},
	ANA_AnalyticsScan:function(){
		//埋点
		//重新扫描整个页面
		(new Analytics).scan();//打点CA绑定数据
	},
	/*setTitle:function(titleValue){
		document.title = titleValue;

		const mobile = navigator.userAgent.toLowerCase();
		const length = document.querySelectorAll('iframe').length;

		if (/iphone|ipad|ipod/.test(mobile) && !length) {
			document.title = titleValue;
		  const iframe = document.createElement('iframe');
		  iframe.style.cssText = 'display: none; width: 0; height: 0;';
		  iframe.setAttribute('src', 'about:blank');
		  iframe.addEventListener('load', () => {
		    setTimeout(() => {
		      iframe.removeEventListener('load', false);
		      document.body.removeChild(iframe);
		    }, 0);
		  });
		  document.body.appendChild(iframe);
		}
	},*/
	isIOSWechat: function(){
		var ua = navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i)=="micromessenger" && ua.indexOf('iphone') > 0) {
			return true
		} else {
			return false
		}
	},
	setTitleAgain: function(titleValue, iframe){
		document.title = titleValue;
    // 判断是否为ios设备，ios设备需要通过加载iframe来刷新title
	    if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
	      // iframe = '/favicon.ico?' + Math.random()
	    }
	    return iframe;
	},
	carplateValidate: function(carplate) {
		var isPlate = /^[A-Z]{1}[A-Z_0-9]{6,7}$/; //车牌正则验证
		if(carplate) {
			if(!isPlate.test(carplate)) {
				Toast("车牌格式错误！");
				return false;
			}
		} else {
			Toast("亲，请填写车牌号！");
			return false;
		}

	},
		/**
		 * 验证登录
		 * @param {Object} url 当前登录地址
		 * @param {Object} cb  登陆成功回调函数
		 */
		//  checkLogin: function ( url, cb ) {
		//
		//  	var _result = this.getIsLogin();
		//
		//  }

	ajax: function(options) {

        options = options || {};
        options.type = (options.type || "GET").toUpperCase();
        options.dataType = options.dataType || "json";
        options.async = options.async || true;
        var params = this.formatParams(options.data);

        //创建 - 非IE6 - 第一步
        if (window.XMLHttpRequest) {
            var xhr = new XMLHttpRequest();
        } else { //IE6及其以下版本浏览器
            var xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }

        //接收 - 第三步
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var status = xhr.status;
                if (status >= 200 && status < 300) {
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.fail && options.fail(status);
                }
            }
        }

        //连接 和 发送 - 第二步
        if (options.type == "GET") {
            xhr.open("GET", options.url + "?" + params, options.async);
            xhr.send(null);
        } else if (options.type == "POST") {
            xhr.open("POST", options.url, options.async);
            //设置表单提交时的内容类型
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            //console.info(xhr);
            xhr.send(params);
        }
    },

    formatParams: function (data) {
        var arr = [];
        for (var name in data) {
            arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
        }
        arr.push(("v=" + Math.random()).replace(".",""));
        return arr.join("&");
    },
    isApp:function(){
        var ua = window.navigator.userAgent;//获取ua
        if(ua.indexOf("MongoToC")>=0){
           return true;
        }else{
            return false;
        }
    },

	/**
	 * 跳转404页面
	 * @param {String} code 错误代码
	 */
	goNotFound: function(code) {
		if ( typeof code == 'object' || isNaN(code) ) {
			code = '';
		}

//		window.location.href = code ? 'http://h.jia.sit.com/errorMsg404.htm?code=' + code : 'http://h.jia.sit.com/errorMsg404.htm';
		window.location.href = code ? process.env.HOST_NAME + '/errorMsg404.htm?code=' + code : process.env.HOST_NAME + '/errorMsg404.htm';
	},
    path:function(){
        var env = process.env.NODE_ENV;
        return env === 'development' ? '' : '/cx/cxj/cxjweb';
    },
    isHtml:function(){
        var env = process.env.NODE_ENV;
        return env === 'development' ? 'html' : 'shtml';
    },
    getChannel:function(){
        var userAgent = window.navigator.userAgent,endType;
        if(userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger'){//判断是否是微信
            endType = 'wxCode';
        }else if(userAgent.indexOf('MongoToC') > 0){//判断是否来自APP
            endType = 'appCode';
        }else{//来自H5
            endType = 'h5Code';
        }
        return endType;
    },
    /* 设置cookie函数 */
      setCookie: (key, value, day) =>{
        var date=new Date();
        date.setDate(date.getDate()+day);
        document.cookie=key+'='+escape(value)+';expires='+date;
      },
      /* 获取cookie函数 */
      getCookie: (key) => {
        var coo=unescape(document.cookie);//解码
        var arr1=coo.split('; ');//第一次分解后是数组
        for (var i=0;i<arr1.length;i++){//第二次循环拆分数组
          var arr2=arr1[i].split('=');
          if(arr2[0]==key){
              return arr2[1];
          }
        }
      },
      /* 删除cookie */
      removeCookie: (key) => {
        setCookie(key,'',-1);
      },
      //检测appversion是否大于3.5
     checkAppversionIsGt35:()=>{
        //判断AppVersion
        try{
          var ua = JSON.parse(window.navigator.userAgent), 
              appVersion = ua.appVersion;  
              console.log(ua);
          if(appVersion){
            var ava = appVersion.replace(".","");
            if(ava>=40){
              return true;
            }else return false;
          }else return false;
        }catch(e){
          console.log('ua未获取到');
        }
      },
      //App分享
      appShare:(e, fn)=>{
        var shareObj = e.shareObj, _this = this,  
         
        //分享朋友文案
        title = shareObj.friend.title,
        link = shareObj.friend.link,
        desc = shareObj.friend.desc,
        imgUrl = shareObj.friend.imgUrl,
        //分享朋友圈文案
        Qtitle = shareObj.friendQuan.title,
        Qlink = shareObj.friendQuan.link,
        Qdesc = shareObj.friendQuan.desc,
        QimgUrl = shareObj.friendQuan.imgUrl;

        var isGt35 = _this.a.checkAppversionIsGt35(),
            initRunFlag = e.hasOwnProperty('initRunFlag') ? e.initRunFlag : true;
         
        //当传入initRunFlag为false, 如果appVersion是3.5及以下的，就不执行
        if( !isGt35){
            console.log("appversion小于等于3.5")
            //3.5及以下调用
            lb.shareInfo({
                title : desc,
                url : link,
                content : title,
                imgUrl :imgUrl
            } ,function (data) {
                if(data.errorCode == 0){
                  Toast("分享成功");
                  if(typeof fn=="function"){
                    fn(data);
                  }
                }else{
                    Toast("分享失败");
                    console.log(data.msg);
                }
                
            })
            
        }
        if ( isGt35 ) {
            console.log("appversion大于3.5")
             //4.0及以上调用
             var shareData = {
                url :link,
                title :title,
                content :desc,
                imgUrl : imgUrl
             };
             var shareDataQuan = {
                url :Qlink,
                title :Qtitle,
                content :Qdesc,
                imgUrl : QimgUrl
             }
             //打开菜单
             lb.showMenu()
            
            //分享内容
            lb.menuShareMsg({
                wx:shareData,
                wxtl:shareDataQuan
            })
           
            
        }      
    },
    //微信分享
    wxShare: (obj, fn)=>{
        var url = window.location.href, e = this, t = obj, wxDomain = t.signUrl + '/wxoauth2/s/getShareArgs.htm?url='+url, shareObj = t.shareObj,
         
        //分享朋友文案
        title = shareObj.friend.title,
        link = shareObj.friend.link,
        desc = shareObj.friend.desc,
        imgUrl = shareObj.friend.imgUrl,
        //分享朋友圈文案
        Qtitle = shareObj.friendQuan.title,
        Qdesc = shareObj.friendQuan.desc,
        Qlink = shareObj.friendQuan.link,
        QimgUrl = shareObj.friendQuan.imgUrl;

        t.$http.jsonp(wxDomain).then((res)=>{
          var data=res.data;
            wx.config({
                 debug: false, // 开启调试模式
                 appId: data.appId, // 必填，公众号的唯一标识
                 timestamp: data.timestamp, // 必填，生成签名的时间戳
                 nonceStr: data.nonceStr, // 必填，生成签名的随机串
                 signature: data.signature,// 必填，签名，见附录1
                 jsApiList: [
                    'checkJsApi',
                    'onMenuShareTimeline',
                    'hideOptionMenu',
                    'onMenuShareAppMessage',
                    'getNetworkType',
                    'openLocation',
                    'getLocation'
                   ]
            });

        	wx.ready(function () {
                //分享给朋友
              	wx.onMenuShareAppMessage({
                    title : title, // 分享标题
                    desc : desc, // 分享描述
                    link : link, // 分享链接
                    imgUrl : imgUrl, // 分享图标
                    type : '', // 分享类型,music、video或link，不填默认为link
                    dataUrl : '', // 如果type是music或video，则要提供数据链接，默认为空
                    trigger : function (res) {

                    },
                    success : function () {
                      Toast("分享成功");
                      if(typeof fn=="function"){
                          fn(obj);
                      }
                    },
                    cancel : function () {
                      // 用户取消分享后执行的回调函数
                      Toast("取消分享");
                    },
                    fail : function (res) {
                       Toast("取消失败");

                    }
                });
                //分享到朋友圈
                wx.onMenuShareTimeline({
                  	title : Qdesc, // 分享标题
                    link : Qlink, // 分享链接
                    imgUrl : QimgUrl, // 分享图标
                    trigger : function (res) {
                       console.log("trigger");
                    },
                    success : function () {
                      Toast("分享成功");
                      if(typeof fn=="function"){
                        fn(obj);
                      }
                    },
                    cancel : function () {
                      // 用户取消分享后执行的回调函数
                      Toast("取消分享");
                    },
                    fail : function (res) {
                      Toast("分享失败");
                    }
                });
                
        	});

	        wx.error(function (type, res) {
	
	        });

	        //防止首页不能进行分享
	        function onBridgeReady() {
	            wx.showOptionMenu();
	        }
	        if (typeof WeixinJSBridge == "undefined") {
	            if (document.addEventListener) {
	                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
	            } else if (document.attachEvent) {
	                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
	                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
	            }
	        } else {
	            onBridgeReady();
	        }
	        wx.showMenuItems({
	            menuList : ['menuItem:share:appMessage', 'menuItem:share:timeline']
	        });
        },(err)=>{

        });
      },
 initWxShare:function(e, wxdomain, shareObj, pageFlag){
        console.log("======",pageFlag);
        var dateParam = window.location.href;
        var _this = this;
        var initSignUrl = wxdomain + '/wxoauth2/s/getShareArgs.htm?url='+dateParam;
        e.$http.jsonp(initSignUrl).then(function(d){
            var data=d.data;
            wx.config({
                 debug: false, // 开启调试模式
                 appId: data.appId, // 必填，公众号的唯一标识
                 timestamp: data.timestamp, // 必填，生成签名的时间戳
                 nonceStr: data.nonceStr, // 必填，生成签名的随机串
                 signature: data.signature,// 必填，签名，见附录1
                 jsApiList: [
                    'checkJsApi',
                    'onMenuShareTimeline',
                    'hideOptionMenu',
                    'onMenuShareAppMessage',
                    'getNetworkType',
                    'openLocation',
                    'getLocation'
                   ]
            });

            wx.ready(function () {
                //分享给朋友
                  wx.onMenuShareAppMessage({
                    title : shareObj.friend.shareTitle, // 分享标题
                    desc : shareObj.friend.descContent, // 分享描述
                    link : shareObj.friend.lineLink, // 分享链接
                    imgUrl : shareObj.friend.imgUrl, // 分享图标
                    type : '', // 分享类型,music、video或link，不填默认为link
                    dataUrl : '', // 如果type是music或video，则要提供数据链接，默认为空
                    trigger : function (res) {

                    },
                    success : function () {
                        // 用户确认分享后执行的回调函数
                      //var cxId = common.getCookie("wemall_cxid_c");
                         //console.log(cxId,"cxId");
                         //var a = { activeCode: "FREELUNCH", cxId: cxId }
                         /*_this.$http.post(_this.isdev()+"/bwcactive/partInWXShare/FREELUNCH.htm").then(function(d){
                          window.location.reload();
                            console.info(d);
                         },function(err){
                            Toast(err);
                         })*/
                      _this.shareSucess(e, pageFlag);

                    },
                    cancel : function () {
                        // 用户取消分享后执行的回调函数
                      Toast("取消分享");
                    },
                    fail : function (res) {
                       Toast("取消失败");

                    }
                });
                //分享到朋友圈
                wx.onMenuShareTimeline({
                    title : shareObj.friendQuan.shareTitle, // 分享标题
                    link : shareObj.friendQuan.lineLink, // 分享链接
                    imgUrl : shareObj.friendQuan.imgUrl, // 分享图标
                    trigger : function (res) {
                       console.log("trigger");
                    },
                    success : function () {
                         //var cxId = common.getCookie("wemall_cxid_c");
                         //console.log(cxId,"cxId");
                         //var a = { activeCode: "FREELUNCH", cxId: cxId }
                         /*_this.$http.post(_this.isdev()+"/bwcactive/partInWXShare/FREELUNCH.htm").then(function(d){
                           window.location.reload();
                            console.info(d);
                         },function(err){
                            Toast(err);
                         })*/
                        _this.shareSucess(e, pageFlag);
                    },
                    cancel : function () {
                      // 用户取消分享后执行的回调函数
                      Toast("取消分享");
                    },
                    fail : function (res) {
                      Toast("分享失败");
                    }
                });
                /*Toast("开始获取定位！");
                wx.getLocation({
                  success: function (res) {
                      Toast("获取定位成功！");
                  },  
                  cancel: function (res) {  
                    //alert('用户拒绝授权获取地理位置');  
                  }  
                });  */
            });

            wx.error(function (type, res) {
    
            });

            //防止首页不能进行分享
            function onBridgeReady() {
                wx.showOptionMenu();
            }
            if (typeof WeixinJSBridge == "undefined") {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            } else {
                onBridgeReady();
            }
            wx.showMenuItems({
                menuList : ['menuItem:share:appMessage', 'menuItem:share:timeline']
            });
           });
    },

   
	shareSucess (t, p){
	    Toast("分享成功");
	    t.$http.post(this.isdev()+"/bwcactive/partInWXShare/FREELUNCH.htm", {"pageFrom":p},{emulateJSON:true}).then(function(d){
        	window.location.reload();
        	console.info(d);
    	},function(err){
        	Toast(err);
    	})
	},
    //获取url中的subCode值
    getQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]); return null;
    }
};

// common.ajax({
//     url: common.isdev()+"/user/checkLogin.htm",
//     type: "POST",
//     async:false,
//     dataType: "json",
//     success: function (response, xml) {
//         console.info('success');
//         // 此处放成功后执行的代码
//     },
//     fail: function (status) {
//         // 此处放失败后执行的代码
//     }
// });